<template>
  <view id="map" class="uni-map"></view>
</template>

<script lang="ts" setup>
import AMapLoader from '@amap/amap-jsapi-loader'
import startIcon from '@/static/images/start.png'
import endIcon from '@/static/images/end.png'
import carIcon from '@/static/images/car.png'
import { onMounted } from 'vue';
import type { ExpressData } from '@/types/order';


interface Props {
  logisticsInfo: ExpressData
}
const props = defineProps<Props>()
onMounted(async () => {
  ; (window as any)._AMapSecurityConfig = {
    securityJsCode: 'd38de6955019842e89194996a461e8dc',
  }

  // 获取物流信息
  const AMap = await AMapLoader.load({
    key: 'fc6bc3717c09e3d439823d9814eca279', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })

  let map = new AMap.Map('map', {
    mapStyle: 'amap://styles/grey', //设置地图的显示样式
  })



  AMap.plugin(['AMap.Driving'], function () {
    const driving = new AMap.Driving({
      map: map, // 表示路线规划显示在创建的map实例上
      showTraffic: false, // 关闭实时交通信息
      hideMarkers: true, // 隐藏起点和终点标记
    })

    console.log('logisticsInfo.value.logisticsInf  ----->  ', props.logisticsInfo.logisticsInfo)
    const start = props.logisticsInfo.logisticsInfo.pop()
    const end = props.logisticsInfo.logisticsInfo.shift()


    //设置自定义起点和终点图标
    const startMarker = new AMap.Marker({
      position: [start?.longitude, start?.latitude],
      icon: startIcon,
      anchor: 'bottom-center',
    })

    const endMarker = new AMap.Marker({
      position: [end?.longitude, end?.latitude],
      icon: endIcon,
      anchor: 'bottom-center',
    })

    const carMarker = new AMap.Marker({
      position: [
        props.logisticsInfo.currentLocationInfo?.longitude,
        props.logisticsInfo.currentLocationInfo?.latitude,
      ],
      icon: carIcon,
      anchor: 'bottom-center',
    })

    map.add(startMarker)
    map.add(endMarker)
    map.add(carMarker)


    //获取起终点规划线路
    driving.search(
      [start?.longitude, start?.latitude],
      [end?.longitude, end?.latitude],
      {
        waypoints: props.logisticsInfo.logisticsInfo
          .map((item) => [item.longitude, item.latitude])
          .reverse(),
      },
      (status: any, result: any) => {
        if (status === 'complete') {
          //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
          //查询成功时，result 即为对应的驾车导航信息
          setTimeout(() => {
            map.setFitView([carMarker])
            map.setZoom(10)
          }, 3000)
          console.log(result)
        } else {
          console.log('获取驾车数据失败：' + result)
        }
      }
    )
  })
})
</script>

<style scoped></style>